package com.shruijin.wy.diy;

import com.shruijin.wy.thread.pool.ThreadPool;

import javax.annotation.PostConstruct;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 封装线程池操作
 *
 * @author :enzo
 */

public class ThreadPoolComponent {

    private ExecutorService executorService;

    private Vector<Callable> queue;

    private Semaphore semaphore;

    private CountDownLatch countDownLatch;

    private final static int DEF_SEP = 2;

    private final static int DEF_COU = 1;

    public ThreadPoolComponent(){
        init();
    }

    @PostConstruct
    private void init() {
        executorService = Executors.newCachedThreadPool();
        queue = new Vector<Callable>();
        semaphore = new Semaphore(DEF_SEP);
        countDownLatch = new CountDownLatch(DEF_COU);
    }

    public void add(Callable callable) {
        queue.add(callable);
    }

    /**
     * 执行队列操作
     */
    public void execute() {

        if (queue.isEmpty()){
            return;
        }
        Callable callable = queue.get(0);
        executorService.execute(() -> {
            CallResult result = callable.exec();
            if (result.getCode() == 200) {
                callable.success(result.getMsg());
            } else {
                callable.error(result.getMsg());
            }
            queue.remove(0);
            execute();
        });
    }


}
